//
//  MyFriendViewController.m
//  MyYiJianKangApp
//
//  Created by 张国文 on 16/4/7.
//  Copyright © 2016年 hangzhouyijiyin. All rights reserved.
//

#import "MyFriendViewController.h"
#import "CeShiModelOfFriendMessage.h"
#import "MyFriendTableViewCell.h"
#import "GroupManagerViewController.h"
#import "NewingFriendModel.h"
#import "NewFriendTableViewCell.h"
#import "FriendSetViewController.h"
#import "AddPeopleAndGroupViewController.h"
#import "SearchMyFriendViewController.h"
#import "MyChatViewController.h"
#import "MyScrollViewInMyFriend.h"
#import "ZGWFriendMessageModel.h"
#import "ZGWNewingFriendModel.h"

#define kCurrentUserToken [[NSUserDefaults standardUserDefaults]objectForKey:@"token"]

@interface MyFriendViewController ()<UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) MyScrollViewInMyFriend *backgroudScrollView; // 背景scorollview
@property (nonatomic, strong) UIView *topWhiteView; // 顶部白色背景
@property (nonatomic, strong) UILabel *blueScrollLabel; // 滑动的蓝色label
@property (nonatomic, strong) UITableView *friendTableView; // 好友tableview

@property (nonatomic, strong) NSMutableDictionary *friendDataDic; // 好友数据字典
@property (nonatomic, strong) NSMutableArray *friendKeyArray; // 好友key
@property (nonatomic, strong) NSMutableDictionary *friendNameDuiYingID; // 好友分组对应的ID
@property (nonatomic, strong) NSMutableDictionary *friendNameDuiYingMemberCount; // 好友分组对应的人数
@property (nonatomic, strong) NSMutableDictionary *isSelectFriendHeaderDic; //判断是否展开
@property (nonatomic, strong) NSMutableArray *allFriendMessageArray; // 所有好友的信息数组

@property (nonatomic, strong) UITableView *newingFriendTableView; // 新朋友tableview
@property (nonatomic, strong) NSMutableArray *newingFriendArray; // 新朋友数组

@property (nonatomic, strong) NSTimer *myTimer; // 检查请求是否超时
@property (nonatomic, assign) NSInteger numberOfTime; // 存储请求时间

@property (nonatomic, strong) NSTimer *newingFriendTimer; // 新朋友计时器
@property (nonatomic, assign) NSInteger numberTimerOfNewFriend; // 新朋友请求时间

@property (nonatomic, assign) __block BOOL woDeHaoYouShouldRefreshWhenXDengYuLing; // 我的好友在滑动到左端的时候需要刷新

@end

@implementation MyFriendViewController

- (void)viewWillAppear:(BOOL)animated
{
    // 是否需要刷新
    NSString *shouldFresh = [[NetStatusHandle shareHandle] getShouldFreshOnLianXiRen];
    if ([shouldFresh isEqualToString:@"YES"]) {
        [[NetStatusHandle shareHandle] setShouldFreshOnLianXiRen:@"NO"];
        [self searchNetAndAddMyFriendData];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    // 关闭动画
    [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
    // 关闭计时器
    [self.myTimer invalidate];
    [self.newingFriendTimer invalidate];
    self.numberOfTime = 0;
    self.numberTimerOfNewFriend = 0;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    // navi的修改
    [self changeNavigation];
    // 添加顶部白色背景
    [self addTopWhiteView];
    
    // 构建背景scrollview
    [self addBackgroundScrollView];
    // 检查网络并添加我的好友数据源
    [self searchNetAndAddMyFriendData];
    
}

// navi的修改
- (void)changeNavigation
{
    [self.navigationController.navigationBar setTranslucent:NO];
    self.navigationItem.title = @"联系人";
    UIImageView *leftImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    leftImageView.image = [UIImage imageNamed:@"houtui"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftImageView];
    UITapGestureRecognizer *leftTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lastPage:)];
    [leftImageView addGestureRecognizer:leftTapGes];
    
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithTitle:@"添加" style:UIBarButtonItemStyleDone target:self action:@selector(add:)];
    rightBarItem.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = rightBarItem;
    
}

#pragma mark - 返回上一页面
- (void)lastPage:(UITapGestureRecognizer *)tapGes
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 检查网络并建立数据源
- (void)searchNetAndAddMyFriendData
{
    if ([[[NetStatusHandle shareHandle] getNetStatus] isEqualToString:@"YES"]) {
        [self addData];
        // 建立计数器
        self.myTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(goTimeOnLianXiRen:) userInfo:nil repeats:YES];
        self.numberOfTime = 0;
        [[NSRunLoop currentRunLoop] addTimer:self.myTimer forMode:NSRunLoopCommonModes];
        // 开启加载动画
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] startAnimation];
    } else {
        NSLog(@"没有网络");
        // 添加提示框
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"通知" Content:kNoNetNoRefresh ToView:self];
    }
    
}

#pragma mark - 新朋友界面检查网络并且添加数据
- (void)searchNetAndAddNewFriendData
{
    if ([[[NetStatusHandle shareHandle] getNetStatus] isEqualToString:@"YES"]) {
        [self addNewingFriendData];
        // 建立计数器
        self.newingFriendTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(goTimeOnXinPengYou:) userInfo:nil repeats:YES];
        self.numberTimerOfNewFriend = 0;
        [[NSRunLoop currentRunLoop] addTimer:self.newingFriendTimer forMode:NSRunLoopCommonModes];
        // 开启加载动画
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] startAnimation];
    } else {
        NSLog(@"没有网络");
        // 添加提示框
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"通知" Content:kNoNetNoRefresh ToView:self];
    }
    

}

#pragma mark - 新朋友界面的请求时间
- (void)goTimeOnXinPengYou:(NSTimer *)timer
{
    self.numberTimerOfNewFriend++;
    NSLog(@"联系人页请求时间:%ld", self.numberTimerOfNewFriend);
    if (self.numberTimerOfNewFriend > kZGWQingQiuChaoShi) {
        NSLog(@"联系人页请求超时");
        self.numberTimerOfNewFriend = 0;
        [self.newingFriendTimer invalidate];
        // 关闭动画
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        // 添加提示框
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"通知" Content:kQingQiuChaoShiNoReFresh ToView:self];
    }
}

#pragma mark - 添加新朋友界面的数据源
- (void)addNewingFriendData
{
    NSString *newFriendUrl = [NSString stringWithFormat:@"%@?token=%@", kZGWNewingFriendLieBiao, kCurrentUserToken];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:newFriendUrl parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        if (!responseObject) {
            return;
        }
        [self.newingFriendTimer invalidate];
        self.numberTimerOfNewFriend = 0;
        // 关闭动画
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        
     //   NSLog(@"新朋友的数据 = %@", responseObject);
        NSArray *friend_ship_requestsArray = [responseObject valueForKey:@"friend_ship_requests"];
        self.newingFriendArray = [NSMutableArray array];
        for (NSDictionary *newingFriendDic in friend_ship_requestsArray) {
            ZGWNewingFriendModel *model = [[ZGWNewingFriendModel alloc] init];
            [model setValuesForKeysWithDictionary:newingFriendDic];
            [self.newingFriendArray addObject:model];
        }
        NSLog(@"新朋友数据数组 = %@", self.newingFriendArray);
        [self.newingFriendTableView reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [self.newingFriendTimer invalidate];
        self.numberTimerOfNewFriend = 0;
        // 关闭动画
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        // 添加提示框
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"通知" Content:kHuoQuDataShiBaiNoRefresh ToView:self];
    }];
}

#pragma mark - 添加数据
- (void)addData
{
    // 建立一个我的好友的测试数据
   // [self addFriendDataSource];
    // 建立一个新朋友数据源
 //   [self addNewFriendDataSource];
    NSString *lianXiRenUrl = [NSString stringWithFormat:@"%@?token=%@", kZGWFriendLieBiao, kCurrentUserToken];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:lianXiRenUrl parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        if (!responseObject) {
            return;
        }
        self.numberOfTime = 0;
        [self.myTimer invalidate];
        // 关闭动画
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
     //   NSLog(@"数据 = %@", responseObject);
        // 好友群组所有数组
        NSArray *friend_groupsArray = [responseObject valueForKey:@"friend_groups"];
        self.friendKeyArray = [NSMutableArray array];
        self.friendDataDic = [NSMutableDictionary dictionary];
        self.friendNameDuiYingID = [NSMutableDictionary dictionary];
        self.friendNameDuiYingMemberCount = [NSMutableDictionary dictionary];
        // 所有好友信息
        self.allFriendMessageArray = [NSMutableArray array];
        for (NSDictionary *groupDic in friend_groupsArray) {
            [self.friendKeyArray addObject:[groupDic valueForKey:@"name"]];
            [self.friendNameDuiYingID setValue:[NSString stringWithFormat:@"%@",[groupDic valueForKey:@"id"]] forKey:[groupDic valueForKey:@"name"]];
            [self.friendNameDuiYingMemberCount setValue:[groupDic valueForKey:@"number"] forKey:[groupDic valueForKey:@"name"]];
            NSArray *membersArray = [groupDic valueForKey:@"members"];
            NSMutableArray *tempArray = [NSMutableArray array];
            for (NSDictionary *tempDic in membersArray) {
                ZGWFriendMessageModel *model = [[ZGWFriendMessageModel alloc] init];
                [model setValuesForKeysWithDictionary:tempDic];
                [tempArray addObject:model];
                [self.allFriendMessageArray addObject:model];
            }
            [self.friendDataDic setValue:tempArray forKey:[groupDic valueForKey:@"name"]];
        }
        
        // 初始化表头展开数组
        self.isSelectFriendHeaderDic = [NSMutableDictionary dictionary];
        for (int i = 0; i < self.friendKeyArray.count; i++) {
            NSString *key = self.friendKeyArray[i];
            // 默认都是未展开
            [self.isSelectFriendHeaderDic setValue:@"NO" forKey:key];
        }
        
        NSLog(@"好友分组名字数组：%@", self.friendKeyArray);
        NSLog(@"好友数据字典:%@", self.friendDataDic);
        NSLog(@"好友分组名字对应的ID：%@", self.friendNameDuiYingID);
        NSLog(@"好友分组对应的成员人数:%@", self.friendNameDuiYingMemberCount);
        [self.friendTableView reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"请求失败");
        // 关闭动画
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        // 添加提示框
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"通知" Content:kHuoQuDataShiBaiNoRefresh ToView:self];
        // 暂停计时器
        [self.myTimer invalidate];
        self.numberOfTime = 0;
    }];
    
}

#pragma mark - 计时器方法
- (void)goTimeOnLianXiRen:(NSTimer *)timer
{
    self.numberOfTime++;
    NSLog(@"联系人页请求时间:%ld", self.numberOfTime);
    if (self.numberOfTime > kZGWQingQiuChaoShi) {
        NSLog(@"联系人页请求超时");
        self.numberOfTime = 0;
        [self.myTimer invalidate];
        // 关闭动画
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        // 添加提示框
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"通知" Content:kQingQiuChaoShiNoReFresh ToView:self];
    }
}

#pragma mark - 添加
- (void)add:(UIBarButtonItem *)barItem
{
    NSLog(@"添加");
    AddPeopleAndGroupViewController *addFriendAndGroupVC = [[AddPeopleAndGroupViewController alloc] init];
    addFriendAndGroupVC.friendOrGroup = @"friend";
    [self.navigationController pushViewController:addFriendAndGroupVC animated:YES];
}

#pragma mark - 添加顶部白色背景
- (void)addTopWhiteView
{
    self.topWhiteView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50 * kAdjustParamater)];
    self.topWhiteView.userInteractionEnabled = YES;
    self.topWhiteView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_topWhiteView];
    // 找人
    UIButton *findPeopleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    //  findPeopleButton.backgroundColor = [UIColor redColor];
    findPeopleButton.frame = CGRectMake((kScreenWidth / 2 - 90 * kAdjustParamater) / 2, 15 * kAdjustParamater, 90 * kAdjustParamater, 25 * kAdjustParamater);
    findPeopleButton.titleLabel.font = [UIFont systemFontOfSize:20 * kAdjustParamater];
    [findPeopleButton setTitleColor:[UIColor colorWithRed:84 / 255.0 green:199 / 255.0 blue:222 / 255.0 alpha:1] forState:UIControlStateNormal];
    [findPeopleButton setTitle:@"我的好友" forState:UIControlStateNormal];
    [findPeopleButton addTarget:self action:@selector(changePage:) forControlEvents:UIControlEventTouchUpInside];
    findPeopleButton.tag = 150;
    [self.topWhiteView addSubview:findPeopleButton];
    // 新朋友
    UIButton *findGroupButton = [UIButton buttonWithType:UIButtonTypeCustom];
    //  findGroupButton.backgroundColor = [UIColor redColor];
    findGroupButton.frame = CGRectMake(kScreenWidth / 2 + (kScreenWidth / 2 - 70 * kAdjustParamater) / 2, 15 * kAdjustParamater, 70 * kAdjustParamater, 25 * kAdjustParamater);
    [findGroupButton setTitle:@"新朋友" forState:UIControlStateNormal];
    findGroupButton.titleLabel.font = [UIFont systemFontOfSize:20 * kAdjustParamater];
   // [findGroupButton setTitleColor:[UIColor colorWithRed:84 / 255.0 green:199 / 255.0 blue:222 / 255.0 alpha:1] forState:UIControlStateNormal];
    [findGroupButton setTitleColor:[[UIColor blackColor] colorWithAlphaComponent:0.5] forState:UIControlStateNormal];
    [findGroupButton addTarget:self action:@selector(changePage:) forControlEvents:UIControlEventTouchUpInside];
    findGroupButton.tag = 151;
    [self.topWhiteView addSubview:findGroupButton];
    
    // 添加灰色条
    UILabel *grayLine = [[UILabel alloc] initWithFrame:CGRectMake(0, self.topWhiteView.bottom - 1 * kAdjustParamater, kScreenWidth, 1 * kAdjustParamater)];
    grayLine.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.1];
    [self.topWhiteView addSubview:grayLine];
    
    // 构建蓝色滚动条
    self.blueScrollLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.topWhiteView.bottom - 3 * kAdjustParamater, kScreenWidth / 2, 3 * kAdjustParamater)];
    self.blueScrollLabel.backgroundColor = [UIColor colorWithRed:84 / 255.0 green:199 / 255.0 blue:222 / 255.0 alpha:1];
    [self.topWhiteView addSubview:_blueScrollLabel];
    
}
- (void)changePage:(UIButton *)button
{
    switch (button.tag) {
        case 150:
        {
            NSLog(@"我的好友");
            [UIView animateWithDuration:0.5 animations:^{
                self.blueScrollLabel.frame = CGRectMake(0, self.blueScrollLabel.frame.origin.y, self.blueScrollLabel.frame.size.width, self.blueScrollLabel.frame.size.height);
                self.backgroudScrollView.contentOffset = CGPointMake(0, 0);
            } completion:^(BOOL finished) {
                
            }];
            UIButton *button1 = (UIButton *)[self.view viewWithTag:151];
            [button1 setTitleColor:[[UIColor blackColor] colorWithAlphaComponent:0.5] forState:UIControlStateNormal];
            UIButton *button2 = (UIButton *)[self.view viewWithTag:150];
            [button2 setTitleColor:kCyanColor forState:UIControlStateNormal];
            break;
        }
        case 151:
        {
            NSLog(@"新朋友");
            [UIView animateWithDuration:0.5 animations:^{
                self.blueScrollLabel.frame = CGRectMake(kScreenWidth / 2, self.blueScrollLabel.frame.origin.y, self.blueScrollLabel.frame.size.width, self.blueScrollLabel.frame.size.height);
                self.backgroudScrollView.contentOffset = CGPointMake(kScreenWidth, 0);
            } completion:^(BOOL finished) {
                
            }];
            UIButton *button1 = (UIButton *)[self.view viewWithTag:150];
            [button1 setTitleColor:[[UIColor blackColor] colorWithAlphaComponent:0.5] forState:UIControlStateNormal];
            UIButton *button2 = (UIButton *)[self.view viewWithTag:151];
            [button2 setTitleColor:kCyanColor forState:UIControlStateNormal];
            break;
        }
        default:
            break;
    }
}

#pragma mark - 构建背景scrollview
- (void)addBackgroundScrollView
{
    self.backgroudScrollView = [[MyScrollViewInMyFriend alloc] initWithFrame:CGRectMake(0, self.topWhiteView.bottom, kScreenWidth, kScreenHeight)];
    self.backgroudScrollView.backgroundColor = [[UIColor greenColor] colorWithAlphaComponent:0.1];
    self.backgroudScrollView.pagingEnabled = YES;
    self.backgroudScrollView.contentSize = CGSizeMake(2 * kScreenWidth, kScreenHeight);
    self.backgroudScrollView.bounces = NO;
    self.backgroudScrollView.delegate = self;
    [self.view addSubview:_backgroudScrollView];
    
    // 添加好友tableView
    [self addFriendTableView];
    
    // 添加新朋友tableview
    [self addNewingFriendTableView];
}


#pragma mark - scrollview代理
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSLog(@"滚动");
    if (scrollView.contentOffset.x == kScreenWidth) {
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        // 进行新朋友数据的请求
        [self searchNetAndAddNewFriendData];
    }
    
    if (scrollView.contentOffset.x == 0) {
        if (self.woDeHaoYouShouldRefreshWhenXDengYuLing == YES) {
            self.woDeHaoYouShouldRefreshWhenXDengYuLing = NO;
            [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
            // 进行我的好友数据的请求
            [self searchNetAndAddMyFriendData];
        }
        
    }
    
    self.blueScrollLabel.frame = CGRectMake(scrollView.contentOffset.x / 2, self.blueScrollLabel.frame.origin.y, self.blueScrollLabel.frame.size.width, self.blueScrollLabel.frame.size.height);
   
    
    if (scrollView.contentOffset.x == 0) {
        // 说明是我的好友
        UIButton *findPeopleButton = (UIButton *)[self.view viewWithTag:150];
        [findPeopleButton setTitleColor:kCyanColor forState:UIControlStateNormal];
        UIButton *findGroupButton = (UIButton *)[self.view viewWithTag:151];
        [findGroupButton setTitleColor:[[UIColor blackColor]colorWithAlphaComponent:0.5]  forState:UIControlStateNormal];
    } else if (scrollView.contentOffset.x == kScreenWidth) {
        // 说明是新朋友
        UIButton *findPeopleButton = (UIButton *)[self.view viewWithTag:151];
        [findPeopleButton setTitleColor:kCyanColor forState:UIControlStateNormal];
        UIButton *findGroupButton = (UIButton *)[self.view viewWithTag:150];
        [findGroupButton setTitleColor:[[UIColor blackColor]colorWithAlphaComponent:0.5]  forState:UIControlStateNormal];
    }

}

#pragma mark - 添加我的好友tableView
- (void)addFriendTableView
{
    self.friendTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 114 * kAdjustParamater) style:UITableViewStyleGrouped];
    self.friendTableView.backgroundColor = [UIColor whiteColor];
    self.friendTableView.dataSource = self;
    self.friendTableView.delegate = self;
    self.friendTableView.bounces = NO;
    self.friendTableView.tag = 200;
    [self.backgroudScrollView addSubview:_friendTableView];
    
    // 设置表头
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 92 * kAdjustParamater)];
    headerView.backgroundColor = [UIColor whiteColor];
    self.friendTableView.tableHeaderView = headerView;

    
    UIView *whiteViewOnTopHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50 * kAdjustParamater)];
    whiteViewOnTopHeader.backgroundColor = [UIColor whiteColor];
    [headerView addSubview:whiteViewOnTopHeader];
    
    UIImageView *searchImageV = [[UIImageView alloc] initWithFrame:CGRectMake(16 * kAdjustParamater, 17 * kAdjustParamater, 20 * kAdjustParamater, 20 * kAdjustParamater)];
    searchImageV.image = [UIImage imageNamed:@"tianjiahaoyoutubiao-tianjia"];
    [whiteViewOnTopHeader addSubview:searchImageV];
    
    UILabel *searchMemberLabel = [[UILabel alloc] initWithFrame:CGRectMake(searchImageV.right + 10 * kAdjustParamater, 20 * kAdjustParamater, 300 * kAdjustParamater, 11 * kAdjustParamater)];
    searchMemberLabel.userInteractionEnabled = YES;
    searchMemberLabel.text = @"输入成员名字/ID";
    searchMemberLabel.font = [UIFont systemFontOfSize:k13Big];
    searchMemberLabel.textColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    [whiteViewOnTopHeader addSubview:searchMemberLabel];
    
    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(searchMember:)];
    [whiteViewOnTopHeader addGestureRecognizer:tapGes];
    
    // 灰色线
    UILabel *grayLabelOnHeaderMiddle = [[UILabel alloc] initWithFrame:CGRectMake(0, 50 * kAdjustParamater, kScreenWidth, 1 * kAdjustParamater)];
    grayLabelOnHeaderMiddle.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.1];
    [headerView addSubview:grayLabelOnHeaderMiddle];
    
    // 下方白色区域
    UIView *fenzuView = [[UIView alloc] initWithFrame:CGRectMake(0, grayLabelOnHeaderMiddle.bottom, kScreenWidth, 41 * kAdjustParamater)];
    fenzuView.userInteractionEnabled = YES;
    fenzuView.backgroundColor = [UIColor whiteColor];
    [headerView addSubview:fenzuView];
    
    // 添加手势
    UITapGestureRecognizer *fenzuTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fenzu:)];
    [fenzuView addGestureRecognizer:fenzuTapGes];

    // 分组管理label
    UILabel *fenZuLabel = [[UILabel alloc] initWithFrame:CGRectMake(20 * kAdjustParamater, 10 * kAdjustParamater, 100 * kAdjustParamater, 20 * kAdjustParamater)];
 //   fenZuLabel.backgroundColor = [[UIColor redColor] colorWithAlphaComponent:0.1];
    fenZuLabel.text = @"分组管理";
    fenZuLabel.textAlignment = NSTextAlignmentLeft;
    fenZuLabel.font = [UIFont systemFontOfSize:k16Big];
    fenZuLabel.textColor = [UIColor blackColor];
    [fenzuView addSubview:fenZuLabel];
    
    // 灰色小箭头
    UIImageView *grayJianTou = [[UIImageView alloc] initWithFrame:CGRectMake((375 - 40) * kAdjustParamater, 10 * kAdjustParamater, 20 * kAdjustParamater, 20 * kAdjustParamater)];
    grayJianTou.image = [UIImage imageNamed:@"grayJianTou"];
    [fenzuView addSubview:grayJianTou];
    
    // 表头底部的灰色条
    UILabel *grayLineOnHeaderBottom = [[UILabel alloc] initWithFrame:CGRectMake(0, 40 * kAdjustParamater, kScreenWidth, 1 * kAdjustParamater)];
    grayLineOnHeaderBottom.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.1];
    [fenzuView addSubview:grayLineOnHeaderBottom];
    
}

#pragma mark - 搜索
- (void)searchMember:(UITapGestureRecognizer *)tapGes
{
    NSLog(@"搜索");
    SearchMyFriendViewController *searchMyFriendVC = [[SearchMyFriendViewController alloc] init];
    searchMyFriendVC.friendData = [NSMutableArray arrayWithArray:self.allFriendMessageArray];
    UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:searchMyFriendVC];
    [self presentViewController:naVC animated:YES completion:nil];
}

#pragma mark - 分组管理
- (void)fenzu:(UITapGestureRecognizer *)tapGes
{
    NSLog(@"分组管理");
    GroupManagerViewController *groupManagerVC = [[GroupManagerViewController alloc] init];
    groupManagerVC.groupArray = [NSMutableArray arrayWithArray:self.friendKeyArray];
    groupManagerVC.groupNameDuiYingDic = [NSMutableDictionary dictionaryWithDictionary:self.friendNameDuiYingID];
  //  __block MyFriendViewController *mySelf = self;
    groupManagerVC.groupManagerVCBlock = ^void(NSString *string) {
      //  [mySelf searchNetAndAddMyFriendData];
    };
    [self.navigationController pushViewController:groupManagerVC animated:YES];
}

#pragma mark - 添加新朋友tableview
- (void)addNewingFriendTableView
{
    self.newingFriendTableView = [[UITableView alloc] initWithFrame:CGRectMake(kScreenWidth, 0, kScreenWidth, kScreenHeight - 114 * kAdjustParamater)];
    self.newingFriendTableView.backgroundColor = [UIColor whiteColor];
    self.newingFriendTableView.dataSource = self;
    self.newingFriendTableView.delegate = self;
    self.newingFriendTableView.bounces = NO;
//    self.newingFriendTableView.alwaysBounceHorizontal = YES;
//    self.newingFriendTableView.alwaysBounceVertical = NO;
    self.newingFriendTableView.tag = 201;
    [self.backgroudScrollView addSubview:_newingFriendTableView];
}

#pragma mark - 建立一个我的好友的测试数据
- (void)addFriendDataSource
{
    NSDictionary *dicFriend1 = @{@"_friendImage": @"", @"_name": @"我叫张国文", @"_gender": @"男", @"_myID": @"987654321", @"_mark": @[@"健康达人", @"我爱看电影你呢"]};
    NSDictionary *dicFriend2 = @{@"_friendImage": @"", @"_name": @"王力宏", @"_gender": @"女", @"_myID": @"123456789", @"_mark": @[@"我是运动达人", @"爱看电影"]};
    NSDictionary *dicFriend3 = @{@"_friendImage": @"", @"_name": @"陶喆", @"_gender": @"男", @"_myID": @"123456789", @"_mark": @[@"我是运动达人", @"爱看电影"]};
    NSDictionary *dicFriend4 = @{@"_friendImage": @"", @"_name": @"带秋天", @"_gender": @"女", @"_myID": @"123456789", @"_mark": @[@"我是运动达人", @"爱看电影"]};
    NSArray *firstArray = [NSArray arrayWithObjects:dicFriend1,dicFriend2, dicFriend3, dicFriend4, nil];
    
    NSDictionary *dicFriend5 = @{@"_friendImage": @"", @"_name": @"taylorswift", @"_gender": @"女", @"_myID": @"987654321", @"_mark": @[@"健康达人", @"我爱看电影你呢"]};
    NSDictionary *dicFriend6 = @{@"_friendImage": @"", @"_name": @"金沙", @"_gender": @"女", @"_myID": @"123456789", @"_mark": @[@"我是运动达人", @"爱看电影"]};
    NSArray *secondArray = [NSArray arrayWithObjects:dicFriend5, dicFriend6, nil];
    
    NSDictionary *dicFriend7 = @{@"_friendImage": @"", @"_name": @"周杰伦", @"_gender": @"男", @"_myID": @"987654321", @"_mark": @[@"健康达人", @"我爱看电影你呢"]};
    NSDictionary *dicFriend8 = @{@"_friendImage": @"", @"_name": @"杨幂", @"_gender": @"女", @"_myID": @"123456789", @"_mark": @[@"我是运动达人", @"爱看电影"]};
    NSDictionary *dicFriend9 = @{@"_friendImage": @"", @"_name": @"习近平", @"_gender": @"男", @"_myID": @"123456789", @"_mark": @[@"我是运动达人", @"爱看电影"]};
    
    NSArray *thirdArray = [NSArray arrayWithObjects:dicFriend7, dicFriend8, dicFriend9, nil];
    
    NSDictionary *dicFriend10 = @{@"_friendImage": @"", @"_name": @"奥巴马", @"_gender": @"男", @"_myID": @"123456789", @"_mark": @[@"我是运动达人", @"爱看电影"]};
    NSArray *fourArray = [NSArray arrayWithObjects:dicFriend10, nil];
    
    NSDictionary *moniDataDic = [NSDictionary dictionaryWithObjectsAndKeys:firstArray,@"第一组", secondArray, @"第二组", thirdArray, @"第三组",  fourArray, @"第四组", nil];
    
    // 初始化好友数据字典
    self.friendDataDic = [NSMutableDictionary dictionary];

    
    NSArray *keyArray = [moniDataDic allKeys];
    for (int i = 0; i < keyArray.count; i++) {
        NSString *key = keyArray[i];
        NSArray *tempArray = [moniDataDic valueForKey:key];
        NSMutableArray *dataArray = [NSMutableArray array];
        for (NSDictionary *tempDic in tempArray) {
            CeShiModelOfFriendMessage *model = [[CeShiModelOfFriendMessage alloc] init];
            [model setValuesForKeysWithDictionary:tempDic];
            [dataArray addObject:model];
        }
        [self.friendDataDic setValue:dataArray forKey:key];
    }
    
    NSArray *sortArray = [[moniDataDic allKeys] sortedArrayUsingSelector:@selector(compare:)];
    self.friendKeyArray = [NSMutableArray arrayWithArray:sortArray];
    
    
    // 初始化表头展开数组
    self.isSelectFriendHeaderDic = [NSMutableDictionary dictionary];
    for (int i = 0; i < keyArray.count; i++) {
        NSString *key = keyArray[i];
        // 默认都是未展开
        [self.isSelectFriendHeaderDic setValue:@"NO" forKey:key];
    }
}

#pragma mark - 建立一个新朋友数据源
- (void)addNewFriendDataSource
{
    // 测试数据
    NSDictionary *dic1 = [NSDictionary dictionaryWithObjectsAndKeys:@"鸣人", @"_name", @"我是名人，我想加你为好友", @"_mark", @"YES", @"_isHaveAgree", nil];
    NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:@"大蛇丸", @"_name", @"我是大蛇丸，我想加你为好友", @"_mark", @"NO", @"_isHaveAgree", nil];
    NSDictionary *dic3 = [NSDictionary dictionaryWithObjectsAndKeys:@"波风.水门", @"_name", @"波风.水门，我是我想加你为好友", @"_mark", @"NO", @"_isHaveAgree", nil];
    NSArray *newFriendArray = [NSArray arrayWithObjects:dic1, dic2, dic3, nil];
    self.newingFriendArray = [NSMutableArray array];
    for (NSDictionary *tempDic in newFriendArray) {
        NewingFriendModel *model = [[NewingFriendModel alloc] init];
        [model setValuesForKeysWithDictionary:tempDic];
        [self.newingFriendArray addObject:model];
    }
    
}


#pragma mark - tableview代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView.tag == 200) {
        // 说明是我的好友
        return self.friendKeyArray.count;
    }
    // 说明是新朋友
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag == 200) {
        // 说明是我的好友
        NSString *key = self.friendKeyArray[section];
        NSArray *value = self.friendDataDic[key];
        if ([self.isSelectFriendHeaderDic[key] isEqualToString:@"NO"]) {
            // 说明不能展开
            return 0;
        } else {
            return value.count;
        }
 
    }
    // 说明是新朋友
    return self.newingFriendArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 200) {
        // 说明是我的好友,cell不能复用
        static NSString *identifier = @"friendCell";
        MyFriendTableViewCell *friendCell = [[MyFriendTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        
        // 取得model
        NSString *key = self.friendKeyArray[indexPath.section];
        NSArray *valueArray = self.friendDataDic[key];
     //   friendCell.model = valueArray[indexPath.row];
        friendCell.zgwFriendMessageModel = valueArray[indexPath.row];
        friendCell.selectionStyle = UITableViewCellSelectionStyleNone;
        return friendCell;
    }
    // 说明是新朋友
    static NSString *identifier = @"newingCell";
    NewFriendTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[NewFriendTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell.agreeOrIngoreButton addTarget:self action:@selector(agree:) forControlEvents:UIControlEventTouchUpInside];
    // 取得model
    if (self.newingFriendArray.count > indexPath.row) {
        cell.zgwNewingFriendModel = self.newingFriendArray[indexPath.row];
    }
    
    return cell;
}

#pragma mark - 新朋友中点击同意的回调
- (void)agree:(UIButton *)button
{
    UIView *view = [button superview];
    NewFriendTableViewCell *newingCell = (NewFriendTableViewCell *)[view superview];
    NSIndexPath *tempIndexPath = [self.newingFriendTableView indexPathForCell:newingCell];
    NSLog(@"同意:row = %ld", tempIndexPath.row);
   
//    // 改变model
//    NewingFriendModel *tempModel = self.newingFriendArray[tempIndexPath.row];
//    tempModel.isHaveAgree = @"YES";
//    // 刷新界面
//    [self.newingFriendTableView reloadData];
    
    FriendSetViewController *friendSetVC = [[FriendSetViewController alloc] init];
 //   NSLog(@"mark =%@", tempModel.mark);
    if (self.newingFriendArray.count > tempIndexPath.row) {
        ZGWNewingFriendModel *tempModel = self.newingFriendArray[tempIndexPath.row];
        friendSetVC.markName = tempModel.nikename;
        friendSetVC.applyID = [NSString stringWithFormat:@"%@", tempModel.applyID];
    }
    friendSetVC.fenZuName = [NSMutableArray arrayWithArray:self.friendKeyArray];
    friendSetVC.fenZuNameDuiYingDic = [NSMutableDictionary dictionaryWithDictionary:self.friendNameDuiYingID];
    __block MyFriendViewController *mySelf = self;
    friendSetVC.zgwFriendSetVCBlock = ^void(NSString *string) {
        [mySelf searchNetAndAddNewFriendData];
        self.woDeHaoYouShouldRefreshWhenXDengYuLing = YES;
    };
    [self.navigationController pushViewController:friendSetVC animated:YES];
}


// cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 200) {
        // 说明是我的好友
        return 75 * kAdjustParamater;
    }
    // 说明是新朋友,动态进行高度的布局
    NewFriendTableViewCell *cell = (NewFriendTableViewCell *)[self tableView:self.newingFriendTableView cellForRowAtIndexPath:indexPath];
    return cell.liuYanLabel.bottom + 15 * kAdjustParamater;
}

// 返回分区表头
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView.tag == 200) {
        // 获取key
        NSString *key = self.friendKeyArray[section];
        // 获取对应key的成员数量
        NSString *memberCount = [self.friendNameDuiYingMemberCount valueForKey:key];
        UIView *grayVIew = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 25 * kAdjustParamater)];
        grayVIew.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.03];
        grayVIew.tag = section + 300;
        UIImageView *selectImage = [[UIImageView alloc] initWithFrame:CGRectMake(20 * kAdjustParamater, 2 * kAdjustParamater, 20 * kAdjustParamater, 20 * kAdjustParamater)];
        // 获取是否选择
        NSString *isSelected = [self.isSelectFriendHeaderDic valueForKey:key];
        if ([isSelected isEqualToString:@"NO"]) {
            selectImage.image = [UIImage imageNamed:@"huisejiantou-createGroup"];
        } else {
            selectImage.image = [UIImage imageNamed:@"cyanjiantou-createGroup"];
        }
        [grayVIew addSubview:selectImage];
        UILabel *result = [[UILabel alloc] initWithFrame:CGRectMake(selectImage.right + 10 * kAdjustParamater, 2 * kAdjustParamater, 200 * kAdjustParamater, 20 * kAdjustParamater)];
        // result.backgroundColor = [UIColor redColor];
        
        result.text = [NSString stringWithFormat:@"%@ (%@)", key, memberCount];
        result.textColor = kCyanColor;
        result.textAlignment = NSTextAlignmentLeft;
        result.font = [UIFont systemFontOfSize:k13Big];
        [grayVIew addSubview:result];
        
        // 添加手势
        UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeMember:)];
        [grayVIew addGestureRecognizer:tapGes];
        return grayVIew;
    }
    return nil;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView.tag == 200) {
        // 说明是我的好友
        return 25 * kAdjustParamater;
    }
    // 说明是新朋友
    return 0;
 
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 3 * kAdjustParamater;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 3 * kAdjustParamater)];
    view.backgroundColor = [UIColor whiteColor];
    return view;
}

#pragma mark - 点击表头回调
- (void)changeMember:(UITapGestureRecognizer *)tapGes
{
    NSInteger section = tapGes.view.tag - 300;
    NSString *key = self.friendKeyArray[section];
    // 改变选中状态
    NSString *isSelected = self.isSelectFriendHeaderDic[key];
    if ([isSelected isEqualToString:@"NO"]) {
        [self.isSelectFriendHeaderDic setValue:@"YES" forKey:key];
    } else {
        [self.isSelectFriendHeaderDic setValue:@"NO" forKey:key];
    }
    [self.friendTableView reloadData];
}

#pragma mark - cell的点击回调
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 200) {
        // 说明是我的好友
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
        NSString *key = self.friendKeyArray[indexPath.section];
        NSArray *valueArray = self.friendDataDic[key];
       
        
        MyChatViewController *myChatVC = [[MyChatViewController alloc] init];
        myChatVC.conversationType = ConversationType_PRIVATE;
        if (valueArray.count > indexPath.row) {
            ZGWFriendMessageModel *model = valueArray[indexPath.row];
            NSLog(@"名字:%@", model.nikename);
            myChatVC.title = model.nikename;
            myChatVC.targetId = model.user_id;
            myChatVC.fenZuNameArray = [NSMutableArray arrayWithArray:self.friendKeyArray];
            myChatVC.fenZuNameDuiIDDic = [NSMutableDictionary dictionaryWithDictionary:self.friendNameDuiYingID];
            // 取出对应section对应的小组名字
            myChatVC.userIdOnGroupName = self.friendKeyArray[indexPath.section];
        }
        [self.navigationController pushViewController:myChatVC animated:YES];
        
    } else if (tableView.tag == 201) {
        // 说明是新朋友
        if (self.newingFriendArray.count > indexPath.row) {
            ZGWNewingFriendModel *model = self.newingFriendArray[indexPath.row];
            NSLog(@"名字:%@", model.nikename);
        }
        
    }
    
}

#pragma mark - 左拉删除
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 200) {
        // 说明是我的好友
        return NO;
    }
    // 说明是新朋友
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 200) {
        // 说明是我的好友
        return UITableViewCellEditingStyleNone;
    }
    // 说明是新朋友
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 201) {
        // 只删除新朋友
        if (editingStyle == UITableViewCellEditingStyleDelete) {
            // 开始动画
            [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] startAnimation];
            // 删除对应的好友申请url
            NSString *deleteFriendApplyUrl = [NSString stringWithFormat:@"%@?token=%@", kZGWDeleteFriendApply, kCurrentUserToken];
            // 获取当前的申请人ID
            NSString *applyID = @"";
            if (self.newingFriendArray.count > indexPath.row) {
                ZGWNewingFriendModel *newingFriendModel = self.newingFriendArray[indexPath.row];
                applyID = [NSString stringWithFormat:@"%@", newingFriendModel.applyID];
            }
            NSDictionary *paramaterDic = @{@"friend_request_id":applyID};
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            [manager DELETE:deleteFriendApplyUrl parameters:paramaterDic success:^(NSURLSessionDataTask *task, id responseObject) {
                // 关闭动画
                [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
                NSDictionary *statusDic = [responseObject valueForKey:@"status"];
                NSString*msgString = [statusDic valueForKey:@"msg"];
                if ([msgString isEqualToString:@"delete success"]) {
                    // 删除成功
                    // 删除数据
                    if (self.newingFriendArray.count > indexPath.row) {
                        [self.newingFriendArray removeObjectAtIndex:indexPath.row];
                        [self.newingFriendTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
                    }
                    
                }
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                // 关闭动画
                [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
                [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"提示" Content:@"删除失败，请重试" ToView:self];
            }];
            
            
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
